# -*- coding: utf8 -*-

from __future__ import absolute_import, unicode_literals
import os
from flask import Flask, request, abort, render_template
from wechatpy.enterprise.crypto import WeChatCrypto
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.enterprise.exceptions import InvalidCorpIdException
from wechatpy.enterprise import parse_message, create_reply
from wechatpy import WeChatClient
from wechatpy.enterprise.client.api import WeChatMessage
from wechatpy.enterprise import WeChatClient

import db
from selenium import webdriver
import requests
import random
import string
import time
import json
from datetime import datetime, timedelta
import hashlib

class Sign:
    def __init__(self, jsapi_ticket, url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': jsapi_ticket,
            'timestamp': self.__create_timestamp(),
            'url': url
        }

    def __create_nonce_str(self):
        return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))

    def __create_timestamp(self):
        return int(time.time())

    def sign(self):
        string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
        self.ret['signature'] = hashlib.sha1(string.encode('utf-8')).hexdigest()
        return self.ret

#企业号中微投票
''' TOKEN = os.getenv('WECHAT_TOKEN', 'lhq')
EncodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', 'qUQHSoit5zhmEaTJStNYzyt6oUKJp25ILJ47QfGrXCk')
CorpId = os.getenv('WECHAT_CORP_ID', 'wxa355b9041c07a137')
Secret = os.getenv('WECHAT_SECRET', 'nfhnyakevKNZ7BUCesU11rLVLr5q8W6o-916swxw1U8')
Agentid = os.getenv('WECHAT_AGENTID', '44') '''


#企业号中测试专用
''' TOKEN = os.getenv('WECHAT_TOKEN', 'WxmqchjNhZ4Gg5BYkdB0tlzhwjZ')
EncodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', 'PIU7ngAqiYQvWfHlivg3NkMFGYmc6qkxcg1eLD67pMr')
CorpId = os.getenv('WECHAT_CORP_ID', 'wxa355b9041c07a137')
Secret = os.getenv('WECHAT_SECRET', 'C9zcHMDbPCUvJ4zd-DlUY0aoPXL4wcl9TpB7qJW4GNA')
Agentid = os.getenv('WECHAT_AGENTID', '49') '''

#景德镇
TOKEN = os.getenv('WECHAT_TOKEN', 'Cwij9TY2yRe0')
EncodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', 'eLKIcYbGSmpQFLxSkScXo4dVq8YwjYc53UDdf6rIXVu')
CorpId = os.getenv('WECHAT_CORP_ID', 'ww3160ba6adb403b67')
Secret = os.getenv('WECHAT_SECRET', 'RdGsOps6DnW80EEG25zZ1bu7hTZ1GAlVrh5ThhlDtFk')
Agentid = os.getenv('WECHAT_AGENTID', '1000010')
 

app = Flask(__name__)
@app.route('/',methods=['GET', 'POST'])
def test():
    #获取 access_token
    at_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CorpId ,Secret)
    #at_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww3160ba6adb403b67&corpsecret=RdGsOps6DnW80EEG25zZ1S3q2a4ipqAVLsLSGGVWIEA"

    r = requests.get(at_url)
    res = r.json()
    access_token = res['access_token']

    #获取从菜单传来的code（识别用户用到）
    code = request.args.get('code', '')

    #获取用户唯一识别码 userid
    uid_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s" % (access_token ,code)
    r = requests.get(uid_url)
    res = r.json()
    UserId = res['UserId']


    signa_url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s" %(access_token)
    r = requests.get(signa_url)
    res = r.json()
    ticket = res['ticket']


    #HTML_URL = "http://jdz.pagekite.me/?code="+code+"&state=1"
    HTML_URL = "http://dzy.pagekite.me/?code="+code+"&state=1"

    print '--------------------------'
    print HTML_URL
    print '--------------------------'
    ticket = ticket#具体获取方法见最上方连接文章
    #获取signature
    sign = Sign(ticket, HTML_URL)
    result = {

        "result":sign.sign()

    }

#响应头 允许跨域访问
    response_heade = {
        'Access-Control-Allow-Origin' : '*'
    }
    return render_template('test.html',
            UserId = UserId,
            sig = result)

@app.route('/login',methods=['GET', 'POST'])
def login():

    userid = request.args.get('userid', '')
    dwid = request.args.get('dwid', '')

    if userid == 'dsj_058d' or userid == 'yyj' or userid == 'dzy':
        svc = db.BIDbQuery()
        sfmc = svc.get_year(dwid)[0]

        return render_template('login.html', 
                userid = userid,
                sfmc=sfmc,
                dwid = dwid
                )
    else:
        return render_template('forbbid.html',
            userid=userid
            )

@app.route('/lhq',methods=['GET', 'POST'])
def lhq():
    userid = 'lhq'
    return render_template('forbbid.html',
            userid=userid
            )

@app.route('/WW_verify_XegbzR6bDq4cPlt4.txt',methods=['GET', 'POST'])
def varify():
    scr = 'XegbzR6bDq4cPlt4'
    return scr

@app.route('/salesman',methods=['GET', 'POST'])
def demo():
    return render_template('Salesman.html',
            )

if __name__ == '__main__':
    app.run('0.0.0.0', debug=True)
